package com.luli.Utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 陆离
 * 2022/5/6 14:10:11
 * 日期工具类
 */
@Slf4j
public class PojoUtil {
    /**
     * 日期向前或者向后推几个日
     *
     * @param dateDate
     * @param count
     * @return
     */
    public static String addDay(String dateDate, int count) {
        String pattern = "yyyyMMdd";
        String startDay = addDay(dateDate, count, pattern);
        return startDay;
    }

    public static String addDay(String dateDate, int count, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        // 将字符串的日期转为Date类型，ParsePosition(0)表示从第一个字符开始解析
        Date date = sdf.parse(dateDate, new ParsePosition(0));
        Date date1 = addDay(date, count);
        return sdf.format(date1);
    }


    public static Date addDay(Date date, int count) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // add方法中的第二个参数n中，正数表示该日期后n天，负数表示该日期的前n天
        calendar.add(Calendar.DATE, count);
        return calendar.getTime();
    }

    /**
     * 获取指定日期最后一天
     *
     * @param date
     * @return
     */
    public static String getLastDayOfMonth(String date) {
        final Calendar cal = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date parse = null;
        try {
            parse = dateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        cal.setTime(parse);
        final int last = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        cal.set(Calendar.DAY_OF_MONTH, last);
        Date time = cal.getTime();
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMdd");
        String format = dateFormat1.format(time);
        return format;

    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getDate() {

        //使用Date创建日期对象
        Date date = new Date();
        log.info("当前的日期是------>" + date);

        /**
         * 创建格式化时间日期类
         *构造入参String类型就是我们想要转换成的时间形式
         */
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String datetime = format.format(date);
        log.info("格式化后的时间------->" + datetime);
        return datetime;
    }

    /**
     * 判空
     *
     * @param inputPara
     * @return
     */
    public static boolean isEmpty(Object inputPara) {
        if (inputPara == null) {
            return true;
        }
        if ((inputPara instanceof String)) {
            return ((String) inputPara).trim().equals("");
        } else if (inputPara instanceof Map) {
            return ((Map) inputPara).isEmpty();
        } else if (inputPara instanceof Object[]) {
            Object[] object = (Object[]) inputPara;
            if (object.length == 0) {
                return true;
            }
        } else if (inputPara instanceof Collection) {
            return ((Collection) inputPara).isEmpty();
        } else if (inputPara instanceof CharSequence) {
            return ((CharSequence) inputPara).length() == 0;
        }
        return false;
    }

    /**
     * 上传图片
     *
     * @param uploadPhoto
     * @param uploadPath
     * @return
     */
    public static HashMap<String, Object> uploadFile(MultipartFile uploadPhoto, String uploadPath) {
        HashMap<String, Object> uploadMap = new HashMap<>();
        //判断该路径是否存在
        File file = new File(uploadPath);
        // 若不存在则创建该文件夹
        if (!file.exists() || PojoUtil.isEmpty(uploadPath)) {
            file.mkdirs();
        }
        //获取上传文件的后缀名
        String fileType = uploadPhoto.getOriginalFilename().substring(uploadPhoto.getOriginalFilename().indexOf("."));
        // 获取上传文件的名称
//        String filename = uploadPhoto.getOriginalFilename();
        // 把文件的名称设置唯一值，uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String filename = uuid + fileType;
        // todo 把文件名存入数据库(此步骤省略)
        // 完成文件上传
        //图片地址
        uploadMap.put("uploadPath", uploadPath + filename);
        //图片名称
        uploadMap.put("filename", filename);

        try {
            uploadPhoto.transferTo(new File(uploadPath, filename));
            uploadMap.put("static", "true");
            return uploadMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        uploadMap.put("static", "false");
        return uploadMap;
    }

    /**
     * 删除指定文件 需要入参为删除目录
     * 例：C:\Users\lenovo\Desktop\photo\12d5f8965cdc447da2e7fcc3159c05aa.png
     *
     * @param deletePath
     * @return
     */
    public static Map<String, Object> deleteFile(String deletePath) {
        Map<String, Object> deleteDirectoryMap = new HashMap<>();
        File dirFile = new File(deletePath);
        if (!dirFile.exists()) {
            // 如果dir对应的文件不存在，或者不是一个目录，则退出
            boolean delete = dirFile.delete();
            if (delete) {
                deleteDirectoryMap.put("static", deletePath + "删除成功");
            } else {
                deleteDirectoryMap.put("static", deletePath + "删除失败");

            }
        }
        deleteDirectoryMap.put("Error", "文件不存在");
        return deleteDirectoryMap;
    }


    /**
     * 根据时间 和时间格式 校验是否正确
     * @param length 校验的长度
     * @param sDate 校验的日期
     * @param format 校验的格式
     * @return
     */
    public static boolean isLegalDate(int length, String sDate,String format) {
        int legalLen = length;
        if ((sDate == null) || (sDate.length() != legalLen)) {
            return false;
        }
        DateFormat formatter = new SimpleDateFormat(format);
        try {
            Date date = formatter.parse(sDate);
            return sDate.equals(formatter.format(date));
        } catch (Exception e) {
            return false;
        }
    }
}
